﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;

namespace DAL
{
    public class Spider
    {
        private static string GetWebContent(string URL)//获取网页源码
        {
            string strResult = "";
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
                request.Timeout = 3000;
                request.Headers.Set("Pragam", "no-cache");

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream streamReceive = response.GetResponseStream();
                Encoding encoding = Encoding.GetEncoding("GB2312");
                StreamReader streamReader = new StreamReader(streamReceive, encoding);
                strResult = streamReader.ReadToEnd();
            }
            catch (Exception e)
            {
                throw e.InnerException;
            }
            return strResult;
        }

        public void GetAllCinemaInformation(string url)//获取电影院信息
        {
            string Url = url;
            string strWebContent = GetWebContent(Url);
            string NameRegexStr = "lh10\">([^<]*)</h2>";//影院名匹配正则
            string AddressRegexStr = "mt9\">([^<]*)</dd>";//地址匹配正则
            string TelRegexStr = "mt6\">([^<]*)</dd>";//电话匹配正则
            string Name;
            string Address;
            string Tel;

            var NameResult = Regex.Match(strWebContent, NameRegexStr);
            var AddressResult = Regex.Match(strWebContent, AddressRegexStr);
            var TelResult = Regex.Match(strWebContent, TelRegexStr);

            Name = NameResult.Value;
            Address = AddressResult.Value;
            Tel = TelResult.Value;

            Name = Regex.Replace(Name, "lh10\">", "");
            Name = Regex.Replace(Name, @"</h2>", "");
            Address = Regex.Replace(Address, "mt9\">[\u4e00-\u9fa5]{2}.", "");

            Address = Regex.Replace(Address, "</dd>", "");
            Tel = Regex.Replace(Tel, "mt6\">[\u4e00-\u9fa5]{2}.", "");
            Tel = Regex.Replace(Tel, "</dd>", "");

            ProjectDBEntities pro = new ProjectDBEntities();
            Cinemas c = new Cinemas();
            MovieLists ml = new MovieLists();
            var QueryName = from q in pro.Cinemas select q.name;
            var QueryTime = from q in pro.MovieLists select q.time;
            string[] qn = new string[QueryName.Count()];
            DateTime[] qt = new DateTime[QueryTime.Count()];//返回在数据库中查询出的值的数组
            int indexCinema = 0;//数组索引
            int countCinema = 0;//检验所插入元素在数据库中存在的个数
            int indexTime = 0;
            int countTime = 0;
            foreach (var q in QueryName)
            {
                qn[indexCinema] = Convert.ToString(q);//数组赋值
                indexCinema++;
            }
            foreach (var q in QueryTime)
            {
                qt[indexTime] = Convert.ToDateTime(q);//数组赋值
                indexTime++;
            }
            for (int i = 0; i < indexCinema; i++)//检验数据库中是否存在要写入的值
            {
                if (Name == qn[i])
                {
                    countCinema++;
                }
            }
            if (countCinema == 0)//如果不存在进行插入
            {
                c.name = Name;
                c.address = Address;
                c.tel = Tel;
                pro.AddToCinemas(c);
                pro.SaveChanges();
            }

            string tableRegexStr = "mdShowtime\">.*?</dd>";
            var result = Regex.Matches(strWebContent, tableRegexStr);
            string[] Result = new string[result.Count];
            for (int i = 0; i < result.Count; i++)
            {
                Result[i] = result[i].Value;
            }
            for (int i = 0; i < result.Count; i++)
            {
                var timeResult = Regex.Matches(Result[i], "time=\".*?\"");
                var nameResult = Regex.Match(Result[i], "title=\".*?\"");
                var priceResult = Regex.Matches(Result[i], "<em>.*?</em>");
                string MovieName = nameResult.Value;
                string[] Time = new string[timeResult.Count];
                string[] Price = new string[timeResult.Count];

                MovieName = Regex.Replace(MovieName, "title=\"", "");
                MovieName = Regex.Replace(MovieName, "\"", "");
                MovieName = Regex.Replace(MovieName, "/", " ");

                for (int innerindex = 0; innerindex < timeResult.Count; innerindex++)
                {
                    Time[innerindex] = timeResult[innerindex].Value;
                    Price[innerindex] = priceResult[innerindex].Value;
                    Time[innerindex] = Regex.Replace(Time[innerindex], "time=\"", "");
                    Time[innerindex] = Regex.Replace(Time[innerindex], "\"", "");
                    Price[innerindex] = Regex.Replace(Price[innerindex], "<em>", "");
                    Price[innerindex] = Regex.Replace(Price[innerindex], "</em>", "");
                    Price[innerindex] = Regex.Replace(Price[innerindex], "￥", "");
                    for (int ii = 0; ii < indexTime; i++)//检验数据库中是否存在要写入的值
                    {
                        if (Time[innerindex] == qn[ii])
                        {
                            countTime++;
                        }
                    }
                    if (countTime == 0)
                    {
                        ml.cinema = Name;
                        ml.price = Convert.ToDouble(Price[innerindex]);
                        ml.time = Convert.ToDateTime(Time[innerindex]);
                        ml.movie = MovieName;
                        pro.AddToMovieLists(ml);
                        pro.SaveChanges();
                    }
                }
            }
        }

        public void GetAllMovieInformation(string url)//获取电影信息
        {
            string Url = url;
            string MovieName;
            string FDirector;
            string LDirector;
            string FStar;
            string MStar;
            string LStar;
            string ShowTime;
            string Summary;

            string strWebContent = GetWebContent(Url);
            string nameRegexStr = "<title>([^<]*)</title>";
            string direcotrRegexStr = "By\">.*<strong class=\"bold\">主演";
            string starRegexStr = "starring\">.*<strong class=\"bold\">类型";
            string showTimeRegexStr = "class=\"bold\">上映日期.*?</span>";
            string summaryRegexStr = "v:summary\">.*?</span>";

            var nameResult = Regex.Match(strWebContent, nameRegexStr);
            MovieName = nameResult.Value;
            MovieName = Regex.Replace(MovieName, "<title>", "");
            MovieName = Regex.Replace(MovieName, "</title>", "");

            var directorFResult = Regex.Match(strWebContent, direcotrRegexStr);
            FDirector = directorFResult.Value;
            var directorLResult = Regex.Match(FDirector, "By\">.*</a>");
            LDirector = directorLResult.Value;
            LDirector = Regex.Replace(LDirector, "</a>", "");
            LDirector = Regex.Replace(LDirector, "<a.*?href=\"(.*?)\".*?>", "");
            LDirector = Regex.Replace(LDirector, "By\">", "");
            LDirector = Regex.Replace(LDirector, @"\b\s{2,}\b", " ");//获取导演信息列表

            var starFResult = Regex.Match(strWebContent, starRegexStr);
            FStar = starFResult.Value;
            var starMResult = Regex.Match(FStar, "starring\">.*<a");
            MStar = starMResult.Value;
            var starLResult = Regex.Match(MStar, "starring\">.*</a>");
            LStar = starLResult.Value;
            LStar = Regex.Replace(LStar, "</a>", "");
            LStar = Regex.Replace(LStar, "<a.*?href=\"(.*?)\".*?>", "");
            LStar = Regex.Replace(LStar, "starring\">", "");
            LStar = Regex.Replace(LStar, @"\b\s{2,}\b", " ");//获取演员列表

            var showTimeResult = Regex.Match(strWebContent, showTimeRegexStr);
            ShowTime = showTimeResult.Value;
            ShowTime = Regex.Replace(ShowTime, "<span.*?>", "");
            ShowTime = Regex.Replace(ShowTime, "class=\"bold\">上映日期：</strong> .", "");
            ShowTime = Regex.Replace(ShowTime, "</span>", "");//获取上映日期

            var summaryResult = Regex.Match(strWebContent, summaryRegexStr);
            Summary = summaryResult.Value;
            Summary = Regex.Replace(Summary, "v:summary\">", "");
            Summary = Regex.Replace(Summary, "</span>", "");
            Summary = Regex.Replace(Summary, "<p>", "");
            Summary = Regex.Replace(Summary, "</p>", "");
            Summary = Regex.Replace(Summary, "(&nbsp;)*", "");

            ProjectDBEntities pro = new ProjectDBEntities();
            Movies m = new Movies();
            var Query = from q in pro.Movies select q.name;
            string[] sq = new string[Query.Count()];//返回在数据库中查询出的值的数组
            int index = 0;//数组索引
            int count = 0;//检验所插入元素在数据库中存在的个数
            foreach (var q in Query)
            {
                sq[index] = Convert.ToString(q);//数组赋值
                index++;
            }
            for (int i = 0; i < index; i++)//检验数据库中是否存在要写入的值
            {
                if (MovieName == sq[i])
                {
                    count++;
                }
            }
            if (count == 0)
            {
                m.name = MovieName;
                m.director = LDirector;
                m.actors = LStar;
                m.introduction = Summary;
                m.time = Convert.ToDateTime(ShowTime);
                pro.AddToMovies(m);
                pro.SaveChanges();
            }
        }
    }
}
